//
//  LoginViewController.m
//  specialine
//
//  Created by 往返网络 on 17/2/7.
//  Copyright © 2017年 com. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "LoginView.h"          //view
#import "ResetPassViewController.h"  //重设密码界面
#import "RegisterViewController.h" //注册界面
#import "PublicMethod.h"
#define USERNAME @"username"
#define PASSWORD @"password"
#define fontsize 15
#define USERNAME @"username"
#define PASSWORD @"password"
#define ResetEnterType @"loginaccess"  //进入重设密码页面（1）／手机验证页面（2）
//定义登录URL
#define URL_LOGIN [NSString stringWithFormat:@"%@/Appcustomernewer/Login/login?type=get",BASE_URL]
@interface LoginViewController ()<LoginViewDelegate>
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@end

//----------------------设置手机验证码登录方式为2，重设密码登录为1，存于userdefaults中 loginaccess -－－－－－－－－－

@implementation LoginViewController

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    [self createUI];
    
    
    // Do any additional setup after loading the view.
}

- (void)createUI{
    

    LoginView * loginview = [[LoginView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
    
    [self.view addSubview:loginview];
    
    loginview.loginviewDelgate = self;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
}

#pragma makrk ------ - -- - - - -LoginviewDelegate  协议方法-- -- -- - - - -- - - - - - 

 //用于传递用户名，密码
- (void)loginViewClickButtonOfType:(LoginViewButtonType)type withDictionary:(NSDictionary *)usermesdict{

    NSString * phonestring = [usermesdict objectForKey:USERNAME];


    switch (type) {
            
        case LoginViewButtonTypeOfNormalLogin: //正常登陆
            
        {
           #warning ------------------------仅供 测试
            
//            if (![PublicMethod isValidateTel:phonestring])
//                
//            {
//                
//                ALERT(@"提示", @"手机号格式错误", nil, @"确认", nil);
//                
//                return;
//            }
            //数据请求
            [self enterMainvcwithUserDictionary:usermesdict];
            
            break;
            
    }
            case LoginViewButtonTypeOfCannotLogin: //无法登陆
            //弹出alertviewcontroller ,选择手机验证登陆 / 重设密码
            
            [self enterotherLogin];
            
          case LoginViewButtonTypeOfRegister: //注册界面
            
             {
        
            RegisterViewController * registervc = [[RegisterViewController alloc]init];
                 
            [self presentViewController:registervc animated:YES completion:nil];
                 
             }
        default:
            
            break;
    }

}


- (void)enterMainvcwithUserDictionary:(NSDictionary *)dict{
    
    //播放动画
    UIImageView * im = [PublicMethod startAnimation];
  
    NSString * userphone = [dict objectForKey:USERNAME];
    
    NSString * password  =  [dict objectForKey:PASSWORD];
    
    NSString * url = [NSString stringWithFormat:@"%@&mobile=%@&password=%@",URL_LOGIN,userphone,password];
    
    NSLog(@"login url %@",url);
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                // 停止动画
                [im stopAnimating];
             
                //设置本地信息。.
                
                NSUserDefaults * userdefault = [NSUserDefaults standardUserDefaults];
                
                [userdefault setObject:@"islogin" forKey:USERDEFAULTS_ISLOGIN];
                
                [userdefault setObject:userphone forKey:USERDEFAULTS_PHONE];

               // 存储tocken
                [userdefault setObject:dict[@"token"] forKey:USER_TOCKE];
                
                NSLog(@"token %@",[userdefault objectForKey:USER_TOCKE]);
                
                //发通知
                [[NSNotificationCenter defaultCenter]postNotificationName:@"LOGIN" object:nil];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"CHANGE" object:nil];

                AppDelegate * appdele = (AppDelegate *)[[UIApplication sharedApplication]delegate];
                appdele.tabbarcontr.selectedIndex = 0;
                
                //移除登录页面
                [self dismissViewControllerAnimated:YES completion:nil];
                
                [self removeFromParentViewController];
                
                [self.view removeFromSuperview];
                
                //发送主页刷新余额通知
                [[NSNotificationCenter defaultCenter]postNotificationName:@"REFRESH" object:nil];

            }else{
                
                [im stopAnimating];

                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
        [im stopAnimating];

    }];
    
 
    

    
}


#pragma mark --- ----------------------其它方式登录-------------------
- (void)enterotherLogin{

//    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    
//    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//        
//        
//        
//    }];
//    
//    // －－－－－－－－－－－－－－－－－－－  重设密码 －－－－－－－－－－－－－－
//    UIAlertAction * resetpassword = [UIAlertAction actionWithTitle:@"重设密码" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        [self enterLoginType:LoginViewButtonTypeOfResetPassWord];
//        
//        
//    }];
//    
//    
//    // －－－－－－－－－－－－－－－－－－－－手机验证码－－－－－－－－－－－－－
//   UIAlertAction * mobilepasslogin  = [UIAlertAction actionWithTitle:@"手机验证码登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//       
//       
//       [self enterLoginType:LoginViewButtonTypeOfMobileTest];
//       
//
//   }];
//    
//    [alertVC addAction:cancel];
//    
//    [alertVC addAction:resetpassword];
//    
//    [alertVC addAction:mobilepasslogin];
//    
//    [self presentViewController:alertVC animated:YES completion:nil];
    
    [self enterLoginType:LoginViewButtonTypeOfResetPassWord];

}

#pragma mark - - --  - -- - - 进入相应登陆界面 （手机验证 ／ 重设密码） - -- - -- - -- - -
- (void)enterLoginType:(LoginViewButtonType)type{

    ResetPassViewController * resetpassvc = [[ResetPassViewController alloc]init];

    UINavigationController * navreset = [[UINavigationController alloc]initWithRootViewController:resetpassvc];

    switch (type) {
            
        case LoginViewButtonTypeOfMobileTest:
            
            //手机验证界面
            
            resetpassvc.titlestring = @"手机验证码登录";
            
            [self presentViewController:navreset animated:YES completion:nil];
            
            //如果本地登陆成功的值为1，则由重设密码进入，2为手机验证码进入 --
            
            [USERDEFAULTS setObject:@"2" forKey:ResetEnterType];
            
            break;
            
        case LoginViewButtonTypeOfResetPassWord:
            
            //重设密码
            
            resetpassvc.titlestring = @"重设密码";

            [self presentViewController:navreset animated:YES completion:nil];
            
            [USERDEFAULTS setObject:@"1" forKey:ResetEnterType];

            break;
            
        default:
            
            break;
            
    }

}

#pragma mark - - -- - - - 懒加载 ---- - -- - - 

- (AFHTTPSessionManager*)manger{
    
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        
    }
    
    return _manger;
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
